<?php

// TODO: $error should contain values which were unknown
// require "../languages/english_probes.inc.php";

class Probeparser {

	var $error = "";

	var $dbusername  = "";
	var $dbpassword  = "";
	var $dbname      = "";
	var $dbhost      = "";
	var $tablename   = ""; // Reports table
	var $galatable   = ""; // Galaxy table
	var $parserarray = null;



	/**
	* @return downloads
	* @param String $dbusername Username for database
	* @param String $dbpassword Passwprd for database
	* @param String $dbname Name for the galaxytool database
	* @param String $tablename Name of the table with alle probe reports
	* @param String $dbhost Database host
	* @desc Constructor for this class
 	*/
	function Probeparser($dbusername,$dbpassword,$dbname,$tablename,$galatable,$dbhost="localhost") {

		if (!empty($dbusername) && !empty($dbname) && !empty($tablename) && !empty($galatable) && !empty($dbhost)) {
			$this->dbusername = $dbusername;
			$this->dbpassword = $dbpassword;
			$this->dbname     = $dbname;
			$this->tablename  = $tablename;
			$this->galatable  = $galatable;
			$this->dbhost     = $dbhost;
		} else {
			return false;
		}
	}

	/** get Full-format scantime.
	 * @param $short_scantime string. "mm-dd hh:mi:ss"
	 * @return string. "yyyy-mm-dd hh:mi:ss"
	 */
	function getFullScantime($short_scantime) {
		$now = time();
		$curYear = date("Y", $now);
		$sixm = 6*30*24*60*60;	//seconds of 180 days
		$scantime = $short_scantime;
		$scantime1 = $curYear . "-" . $scantime;
		$scantime2 = ($curYear-1) . "-" . $scantime;
		$scantime3 = ($curYear+1) . "-" . $scantime;
		if (strtotime($scantime1) == -1) //invalid format
			return "";
		if (strtotime($scantime1) - $now > $sixm) $scantime = $scantime2;
		elseif (strtotime($scantime1) - $now < -$sixm) $scantime = $scantime3;
		else $scantime = $scantime1;
		return $scantime;
	}
	
	function parseEntry($string,$flush=true) {
		$ogameserver = $_SESSION['s_ogameserver'];
		if($ogameserver == 'ogame.com.cn') {
			include_once("../languages/chinese_probes.inc.php");
		} else if($ogameserver == 'ogame.org') {
			include_once("../languages/english_probes.inc.php");
		} else if($ogameserver == 'ogame.tw') {
			include_once("../languages/taiwanese_probes.inc.php");			
		}
		
		/* include the xxx_probes.inc.php in function body, so we need not global description here
		global $moon_name;
		global $db_array;
		global $top_array;
		*/

		$userid = $_SESSION['s_userid'];
		
		$matches = array();
		
		if($ogameserver == 'ogame.com.cn') {
			$pattern = '/资源在 (.*) \[(\d+:\d+:\d+)\] (\([^)]*\)[\r\n]+)?\s*在 (\d+-\d+ \d+:\d+:\d+)/';
		} else if($ogameserver == 'ogame.org') {
			$pattern = '/Resources on (.*) \[(\d+:\d+:\d+)\] (\([^)]*\)[\r\n]+)?\s*at (\d+-\d+ \d+:\d+:\d+)/';
		} else if($ogameserver == 'ogame.tw') {
			$pattern = '/資源在 (.*) \[(\d+:\d+:\d+)\] (\([^)]*\)[\r\n]+)?\s*在 (\d+-\d+ \d+:\d+:\d+)/';
		}

		if(preg_match($pattern, $string, $matches) == 1) {
			$planetname = trim($matches[1]);
			$planetposition = trim($matches[2]);
			$scantime = trim($matches[4]);
		} else {
			$this->error = "not a valid espionage report, parse failed.";
			return false;
		}
		
		$moon = "false";
		if (preg_match("/.*\(?" . $moon_name . "\)?/", $planetname) == 1) $moon = "true";
		// mess code of spelling of MOON in chinese, 月球 => moon => 鏈堢悆
		if ($moon != "true" && $ogameserver == 'ogame.com.cn' && $planetname == '鏈堢悆') $moon = "true"; 

		$scantime = $this->getFullScantime($scantime);
		mysql_connect($this->dbhost,$this->dbusername,$this->dbpassword) or die(mysql_error());
		$query = "select scantime from " . $this->tablename . " where userid=$userid AND coordinates='".$planetposition."' and moon='".$moon."'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		if($line = mysql_fetch_assoc($res)){
			if(strcmp($line['scantime'],$scantime)>=0){
				$tmp = explode(':', $planetposition);
				$this->error = "<a href=\"view.php?gala=". $tmp[0] . "&system=" . $tmp[1] . "\">" . "[" . $planetposition . "] </a> has been already scaned at ". $line['scantime'];
				return false;
			}
		}

		$espionagetitle = $matches[0];
		$string = substr($string,strpos($string, $espionagetitle)+strlen($espionagetitle));
		$string = str_replace(":"," ",$string);
		if($ogameserver == 'ogame.com.cn') $string = str_replace("："," ",$string);

		$lines = explode("\n",$string);

		$reportarray = array();
		$scanned = "ressources";

		$totalships = 0;
		$ec = 0;
		for ($i=0;$i<count($lines);$i++) {
			if (trim($lines[$i]) == $top_array["Fleets"]) $scanned = "fleet";
			if (trim($lines[$i]) == $top_array["Defence"]) $scanned = "defence";
			if (trim($lines[$i]) == $top_array["Buildings"]) $scanned = "buildings";
			if (trim($lines[$i]) == $top_array["Research"]) $scanned = "research";
			if (strpos($lines[$i],"@") !== false) break;
			if (strpos($lines[$i],"%") !== false) {
				$tmpPosB = strrpos($lines[$i], " ");
				if($tmpPosB === false) {
					$tmpPosB = strrpos($lines[$i], ":");
				}
				if($tmpPosB !== false) {
					$tec = substr($lines[$i], $tmpPosB+1, strrpos($lines[$i], '%')- $tmpPosB -1);
					if(is_numeric($tec)) {
						$ec = (int)$tec;
					}
				}
				break;
			}
			$string = preg_replace('/\s/'," ",$lines[$i]);
			$string = str_replace(".","",$string);
			$content = explode(" ",$string);
			if (count($content) > 1) {
				$name = "";
				for ($j=0;$j<count($content);$j++) {
					if (!is_numeric($content[$j])) $name .= " ".$content[$j];
					else {
						// save current information
						if ($content[$j] < 0) $content[$j] = 0;
						$reportarray[trim($name)] = round($content[$j],0);
						if($scanned == "fleet") $totalships+=round($content[$j],0);
						// clear name for possible next name
						$name = "";
					}
				}
			}
		}

		if (count($reportarray) < 1) {
			$this->error = "No Report found!";
			return false;
		}
		/*
		$reportarray[OT_TOTALSHIPS] = $totalships;
		$reportarray[OT_EC] = $ec;
		*/

		//back up the old record
		$query = "REPLACE ". $this->tablename . "_chg SELECT * FROM ". $this->tablename . " where userid=$userid AND coordinates='".$planetposition."' and moon='".$moon."'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		$query = "REPLACE INTO ".$this->tablename." SET userid=$userid, coordinates='".$planetposition."', moon='".$moon."', ";;
		foreach ($reportarray as $key => $value) {
			if(isset($db_array[$key])) {
				$query .= $db_array[$key]."='".mysql_real_escape_string($value)."',";
			}
		}
		$query .= " totalships=$totalships, ec=$ec, scantime='".$scantime."', scanned='$scanned'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		
		$query = "UPDATE ".$this->galatable." SET reports='true' WHERE userid=$userid AND CONCAT(galaxie,':',system,':',planet)='$planetposition' AND reports<>'true'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		if ($flush) {
			$tmp = explode(':', $planetposition);
			echo "<a href=\"view.php?gala=". $tmp[0] . "&system=" . $tmp[1] . "\">" . $planetposition. "</a> ".PARSER_INFO1."<br>\n";
			flush();
		}
		mysql_close();

		return true;
	}

	/** get an array not contains any array member
	 */
	function serial_array($array) {
		$r = array();
		foreach($array as $key => $val) {
			if(!is_array($val))
				$r[$key] = $val;
			else
				$r = array_merge($r, $this->serial_array($val));
		}
		return $r;
	}
	
	/** parse the serialized php object entry
	 *
	 * e.g.	a:12:{s:2:"zp";s:15:"Niay [2:196:10]";s:4:"hist";s:14:"07-30 10:35:31";s:5:"rost1";d:33381;s:5:"rost2";d:14087;s:5:"rost3";d:1371;s:5: "rost4";d:627;s:13:"GesamtSchiffe";i:0;s:8:"Gebaeude";a:5:{s:6:"金属矿";i: 12;s:6:"晶体矿";i:9;s:10:"重氢分离器";i:3;s:12:"太阳能发电站";i:11;s:10:"研究实验室";i:1;} s:7:"Technik";a:4:{s:10:"计算机技术";i:1;s:8:"能量技术";i:2;s:8:"燃烧引擎";i:1;s:8:"激光技术";i:1;}s:6:"Flotte";i:0;s:12:"Verteidigung";i:0;s:2:"ec";d:0;}
	 */
	function parseEntry2($string,$flush=true) {
		//$curdir = dirname(__FILE__)."/";
		$ogameserver = $_SESSION['s_ogameserver'];
		if($ogameserver != 'ogame.com.cn') return false;
		include_once( "../chinese/class.Chinese.php" );
		include_once("../languages/chinese_probes.inc.php");

		/**
		zp : planet_name [coordiante]
		hist : scan date
		rost1 : metal
		rost2 : crystal
		rost3 : Deuterium
		rost4 : energy
		
		GesamtSchiffe : Total ships
		Gebaeude : Buildings
		Technik : Technology
		Flotte : Fleet
		Verteidigung : Defence
		*/
		$string = trim($string);

		if(function_exists('iconv'))
			$string = iconv('utf-8', 'gb18030', $string);
		else {
		        $_chinese = new Chinese("UTF8", "GB2312", $string);
		        $string = $_chinese->ConvertIT();
		}

		$v = $db_array[R_METAL];
		unset($db_array[R_METAL]);
		$db_array['rost1'] = $v;
		$v = $db_array[R_CRYSTAL];
		unset($db_array[R_CRYSTAL]);
		$db_array['rost2'] = $v;
		$v = $db_array[R_DEUTERIUM];
		unset($db_array[R_DEUTERIUM]);
		$db_array['rost3'] = $v;
		$v = $db_array[R_ENERGY];
		unset($db_array[R_ENERGY]);
		$db_array['rost4'] = $v;
				
		foreach($db_array as $key => $value) {
			unset($db_array[$key]);
			if(function_exists('iconv'))
				$db_array[iconv('utf-8', 'gb18030', $key)] = $value;
			else {
				$_chinese->SourceText = $key;
				$db_array[$_chinese->ConvertIT()] = $value;
			}
		}
		
		$string = preg_replace('/([^[\s:;])(\[\d+:\d+:\d+\])/', '\\1 \\2', $string, 1);
		$matches = array();
		$pattern = '/"\s*([^"]+)\s+(\[\d+:\d+:\d+\])\s*"/';
		if(preg_match($pattern, $string, $matches) == 0) {
			$this->error = "Unrecongnized format!";
			return false;
		}
		$string = str_replace($matches[0], '"' . preg_replace('/[:;]/', '.', $matches[1]) . ' ' . $matches[2] . '"', $string);
		$tmp = explode(';', $string);
		if(count($tmp)<4) {
			$this->error = "Unrecongnized format!";
			return false;
		}
		for($i=0; $i<count($tmp); $i++) {
			$str = $tmp[$i];
			if($i != 1 and $i != 3) {
				$tmp[$i] = str_replace(' ', '', $str);
			} else {
				$tmp1 = explode(':', $str);
				for($j=0; $j<count($tmp1); $j++)
				if($j!=2) $tmp1[$j] = str_replace(' ', '', $tmp1[$j]);
				if(isset($tmp1[2])) $tmp1[2] = trim($tmp1[2]);
				$tmp[$i] = implode(':', $tmp1);
				if($i == 1 && count($tmp1) > 2 && $tmp1[0] == 's' && is_numeric($tmp1[1])) {
					$slen = (int)($tmp1[1]);
					unset($tmp1[0]);
					unset($tmp1[1]);
					$sv = implode(':', $tmp1);
					$sv = substr($sv, 1, strlen($sv)-2);	//eliminate lead and tail quotoes
					$flen = strlen($sv);
					if($flen != 0 && $flen != $slen) {
						if($flen > $slen) {
							$sv = substr($sv, $flen-$slen);
						} else {
							$sv = str_pad($sv, $slen, "?", STR_PAD_LEFT);
						}
						$sv = 's:' . $slen . ':' . '"' . $sv . '"';
						$tmp[$i] = $sv;
						
					}
				}
			}
		}
		$string = implode(';', $tmp);

		// s:11:"防御盾系统 ";
		$shield = "防御盾系统";
		if(function_exists('iconv'))
			$shield = iconv('utf-8', 'gb18030', $shield);
		else {
			$_chinese->SourceText = $shield;
		        $shield = $_chinese->ConvertIT();
		}
		$string = str_replace('s:11:"$shield";', 's:10:"$shield";', $string);

		$rst = unserialize($string);
		if($rst == false || !is_array($rst)) {
			$this->error = "Unrecongnized format!";
			return false;
		}
		
		$moon = "false";

		// get Name & position
		$zp = $rst['zp'];
		$tmp = explode(" ",$zp);
		$tmpc = count($tmp);
		if(preg_match('/^\[\d+:\d+:\d+\]$/', trim($tmp[$tmpc-1])) == 0) {
			$this->error = "Unrecongnized format!";
			return false;
		}
		$planetposition = substr(trim($tmp[$tmpc-1]),1,strlen(trim($tmp[$tmpc-1]))-2);
		unset($tmp[$tmpc-1]);
		$planetname = trim(implode(' ', $tmp));
		if ($planetname == $moon_name) $moon = "true";
		
		// get scan time
		$hist = $rst['hist'];
		$scantime = substr(trim($hist), 0, 14);
		
		//$reportarray = array();
		$scanned = "ressources";
		if(isset($rst['Flotte'])) $scanned = "fleet";
		if(isset($rst['Verteidigung'])) $scanned = "defence";
		if(isset($rst['Gebaeude'])) $scanned = "buildings";
		if(isset($rst['Technik'])) $scanned = "research";

		$reportarray = $this->serial_array($rst);
		
		$totalships = (int)($reportarray['GesamtSchiffe']);
		$ec = (int)($reportarray['ec']);

		unset($reportarray['zp']);
		unset($reportarray['hist']);
		unset($reportarray['GesamtSchiffe']);
		unset($reportarray['Gebaeude']);
		unset($reportarray['Technik']);
		unset($reportarray['Flotte']);
		unset($reportarray['Verteidigung']);
		unset($reportarray['ec']);

		if (count($reportarray) < 1) {
			$this->error = "No Report found!";
			return false;
		}
		
		$scantime = $this->getFullScantime($scantime);
		$userid = $_SESSION['s_userid'];
		mysql_connect($this->dbhost,$this->dbusername,$this->dbpassword) or die(mysql_error());
		mysql_select_db($this->dbname) or die(mysql_error());
		//get the one in db, to see which one is most recently
		$query = "select scantime from " . $this->tablename . " where userid=$userid AND coordinates='".$planetposition."' and moon='".$moon."'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		if($line = mysql_fetch_assoc($res)){
			if(strcmp($line['scantime'],$scantime)>=0){
				$tmp = explode(':', $planetposition);
				$this->error = "<a href=\"view.php?gala=". $tmp[0] . "&system=" . $tmp[1] . "\">" . "[" . $planetposition . "] </a> has been already scaned at ". $line['scantime'];
				return false;
			}
		}
		//back up the old record
		$query = "REPLACE ". $this->tablename . "_chg SELECT * FROM ". $this->tablename . " where userid=$userid AND coordinates='".$planetposition."' and moon='".$moon."'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		$query = "REPLACE INTO ".$this->tablename." SET userid=$userid, coordinates='".$planetposition."', moon='".$moon."', ";;
		foreach ($reportarray as $key => $value) {
			if(isset($db_array[$key])) {
				$query .= $db_array[$key]."='".mysql_real_escape_string($value)."',";
			}
		}
		$query .= " totalships=$totalships, ec=$ec, scantime='".$scantime."', scanned='$scanned'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		
		$query = "UPDATE ".$this->galatable." SET reports='true' WHERE userid=$userid AND CONCAT(galaxie,':',system,':',planet)='$planetposition' AND reports<>'true'";
		$res = mysql_query($query);
		if (!$res) {
			$this->error = $query." ".mysql_error();
			return false;
		}
		if ($flush) {
			$tmp = explode(':', $planetposition);
			echo "<a href=\"view.php?gala=". $tmp[0] . "&system=" . $tmp[1] . "\">" . $planetposition. "</a> ".PARSER_INFO1."<br>\n";
			flush();
		}
		mysql_close();
		return true;		
	}
}

function array_sort($a,$b) {
	if (strlen($a) == strlen($b)) return 0;
	return (strlen($a) > strlen($b)) ? -1 : 1;
}

?>